#!/bin/sh

ver_new="$1"
ver_old="$2"

if [ "$(apk version -t "$ver_old" "1.10.1-r3")" = "<" ]; then
	cat 1>&2 <<-EOF
	*
	* The nginx package has been modified to use dynamic modules. Now there's
	* just single package providing nginx executable and bunch of nginx-mod-*
	* subpackages.
	*
	* Lua support is now provided by package nginx-mod-http-lua, RTMP support
	* is provided by nginx-mod-rtmp.
	*
	* Modules mail and stream are dynamic modules too and so not included
	* by default anymore. If you use them, install nginx-mod-mail and
	* nginx-mod-stream.
	* 
	EOF
fi

# Handle transition from /etc/nginx/conf.d to /etc/nginx/http.d.
if [ "$(apk version -t "$ver_old" '1.18.0-r13')" = '<' ]; then
	default_conf='/usr/share/nginx/http-default_server.conf'

	if [ -z "$(ls -A /etc/nginx/conf.d 2>/dev/null)" ]; then
		# conf.d dir doesn't exist or is empty, so the user doesn't use it.
		# Thus we can install default.conf to the new directory.
		install -m644 "$default_conf" /etc/nginx/http.d/default.conf

	else
		if ! [ -e /etc/nginx/conf.d/default.conf ]; then
			# conf.d dir exists and is not empty, but there's no default.conf
			# file, so the user probably did not modify it and apk has removed
			# it during this upgrade. Prior this version, the default.conf
			# would be installed, so install it now for backward compatibility.
			install -m644 "$default_conf" /etc/nginx/conf.d/default.conf
		fi
		if ! [ -e /etc/nginx/nginx.conf.apk-new ]; then
			# There's no updated nginx.conf, so the user didn't modify this
			# config and apk replaced it during this upgrade. However, the
			# user has some vhost configs in the old directory, so we have
			# to revert the include back to the legacy path.
			sed -i 's|include /etc/nginx/http\.d|# WARNING: Do not use this directory for virtual hosts anymore, use directory http.d!\n\tinclude /etc/nginx/conf.d|' \
				/etc/nginx/nginx.conf
		fi
	fi

	cat >&2 <<-EOF
	*
	* The default and preferred location for nginx vhost configs has been changed
	* from /etc/nginx/conf.d to /etc/nginx/http.d. Although we did our best to not
	* break existing setups by this upgrade, we strongly recommend to verify it.
	*
	EOF
fi

# Handle trasition from /var/tmp/nginx to /var/lib/nginx/tmp
# https://gitlab.alpinelinux.org/alpine/aports/-/issues/11204
if [ -d /var/lib/nginx/tmp ]; then
	for i in /var/tmp/nginx/*; do
		if [ -e "$i" ]; then
			mv $i /var/lib/nginx/tmp/
		fi
	done
	rmdir /var/tmp/nginx 2>/dev/null
fi

exit 0
